//
//  UploadFile.m
//  HuateVideo
//
//  Created by Tiger on 12-8-8.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "UploadFile.h"
#define BASE_URL @"http://222.83.3.156:84/FileInfo.aspx"
#define IMAGE_BASE_URL @"http://222.83.0.89:84/FileInfo.aspx"
#define UPLOAD_URL @"http://222.83.3.156:84/Upload.aspx?guid=%@&index=%d&total=%d&isend=%d"
#define IMAGE_URL @"http://222.83.0.89:84/Upload.aspx?guid=%@&index=%d&total=%d&isend=%d"
#define BUFFER 50 //KB

//222.83.3.156:84 //视频和音乐
//222.83.0.89:84 //图片
//www.crazydasheng.net:8081 //测试服务器

@implementation UploadFile
@synthesize delegate;
@synthesize isUploading;

- (id)init
{
    self = [super init];
    if (self) {
        stop = NO;
        isUploading = NO;
    }
    return self;
}

- (void)startUploadWithVideo:(LocalVideo *)lv
{
    localVideo = [lv retain];
    isUploading = YES;
    [NSThread detachNewThreadSelector:@selector(getServerIndex) toTarget:self withObject:nil];
}

- (void)dealloc
{
    [super dealloc];
}

- (void)storeVideo
{
    [UserDefaults restoreLocalVideo:localVideo];
    [[NSNotificationCenter defaultCenter] postNotificationName:REFLASH_MY_VIDEOS_NOTIFICATION object: nil];
}

- (void)finishedOneUplaod
{
    localVideo.ok = 2;
    [self storeVideo];
    NSLog(@"finished upload name:%@",localVideo.time);
    
    isUploading = NO;
    localVideo = nil;
}

- (void)fieldUpload
{
    //isUploading = NO;
    NSLog(@"field Uploading...");
}

- (void)stopUpload
{
    NSLog(@"stop Uploading...");
    stop = NO;
    isUploading = NO;
    [[NSNotificationCenter defaultCenter] postNotificationName:REFLASH_MY_VIDEOS_NOTIFICATION object: nil];
}

- (void)getServerIndex
{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc]init];
    
    NSInteger package = BUFFER*1024;
    NSData *totalData = [NSData dataWithContentsOfFile:localVideo.storePath];
    CGFloat size = (CGFloat)localVideo.size/1024.0;
    localVideo.total = (NSInteger)ceil(((double)[totalData length])/package);

    
    NSString *strBody = [NSString stringWithFormat:@"guid=%@&userid=%@&type=%@&length=%f&seconds=%d&id=%d&title=%@&describe=%@&name=%@",localVideo.fileid,localVideo.username,localVideo.type,size,localVideo.seconds,localVideo.webid,localVideo.title,localVideo.describe,localVideo.name];
    NSData *dataBody = [strBody dataUsingEncoding:NSUTF8StringEncoding];
    
    NSError *error;
    NSURLResponse *urlResponse;
    
    NSURL *url = [[NSURL alloc]initWithString:[BASE_URL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    
    if ([localVideo.fileType isEqualToString:@"P"]) {
        url = [[NSURL alloc]initWithString:[IMAGE_BASE_URL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    }
    
    
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
    [request setHTTPMethod:@"POST"];
    [request setValue:[NSString stringWithFormat:@"%d",[dataBody length]]forHTTPHeaderField:@"Content-Length"];
    [request setHTTPBody:dataBody];
    NSData *urlData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];
    NSString *responseString = [[NSString alloc] initWithData:urlData encoding:NSUTF8StringEncoding];
    
    NSLog(@"uploaded count >>>>>>> %@",responseString);
    
    NSInteger currentIndex = [responseString intValue];
    if (currentIndex >= 0 && currentIndex < localVideo.total) {
        localVideo.ok = 1;
        [self performSelectorOnMainThread:@selector(storeVideo) withObject:nil waitUntilDone:NO];
        
        NSNumber *progress = [NSNumber numberWithFloat:(((CGFloat)currentIndex)/((CGFloat)localVideo.total))];
        [self performSelectorOnMainThread:@selector(reflashUI:) withObject:progress waitUntilDone:NO];
        
        [self uploadAtIndex:currentIndex];
    }
    else if (currentIndex == localVideo.total) {
        [self performSelectorOnMainThread:@selector(finishedOneUplaod) withObject:nil waitUntilDone:NO];
    }
    else {
        NSLog(@"getServerIndex error...");
        localVideo.ok = 4;
        [self storeVideo];
        [self performSelectorOnMainThread:@selector(fieldUpload) withObject:nil waitUntilDone:NO];
    }
    
    [pool release];
}

- (void)wantToStop
{
    stop = YES;
}

- (void)uploadAtIndex:(NSInteger)currentIndex
{
    NSData *totalData = [NSData dataWithContentsOfFile:localVideo.storePath];
    
    NSInteger index = currentIndex;
    NSInteger package = BUFFER*1024;
    NSInteger total = localVideo.total;
    
    NSLog(@"total >>>>>>>>>>>> %d",total);
    
    NSString *strURL;
    NSURL *url;
    NSMutableURLRequest *request;
    
    NSError *error;
    NSURLResponse *urlResponse;
    NSData *urlData;
    
    NSData *subData;
    NSString *rangeStr;
    
    NSString *guid = localVideo.fileid;
    NSInteger isend;
    
    while (index <= total - 1) {
        
        if (stop) {
            [self performSelectorOnMainThread:@selector(stopUpload) withObject:nil waitUntilDone:NO];
            break;
        }
        
        if (index == total - 1) {
            rangeStr = [NSString stringWithFormat:@"%d,%d",index*package,[totalData length]-index*package];
            subData = [totalData subdataWithRange:NSRangeFromString(rangeStr)];
            isend = 1;
        }
        else {
            rangeStr = [NSString stringWithFormat:@"%d,%d",index*package,package];
            subData = [totalData subdataWithRange:NSRangeFromString(rangeStr)];
            isend = 0;
        }
        
        NSLog(@"buffer index >>>>>>>>>>>> %d",index);
        
        strURL = [NSString stringWithFormat:UPLOAD_URL,guid,index+1,total,isend];
        
        if ([localVideo.fileType isEqualToString:@"P"]) {
            strURL = [NSString stringWithFormat:IMAGE_URL,guid,index+1,total,isend];
        }
        
        url = [[NSURL alloc]initWithString:[strURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
        request = [[NSMutableURLRequest alloc] initWithURL:url];
        [request setHTTPMethod:@"POST"];
        [request setValue:@"multipart/form-data; boundary=AaB03x" forHTTPHeaderField:@"Content-Type"];
        [request setValue:[NSString stringWithFormat:@"%d",[subData length]]forHTTPHeaderField:@"Content-Length"];
        [request setHTTPBody:subData];
        urlData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];
        NSString *responseString = [[NSString alloc] initWithData:urlData encoding:NSUTF8StringEncoding];
        
        NSLog(@"rspStr >>>>>>>>>>>> %@",responseString);
        
        if ([responseString isEqualToString:@"YES"]) {
            NSNumber *progress = [NSNumber numberWithFloat:(((CGFloat)index)/((CGFloat)localVideo.total))];
            [self performSelectorOnMainThread:@selector(reflashUI:) withObject:progress waitUntilDone:NO];
            index ++;
        }
        else {
            NSLog(@"uploadAtIndex error...");
            [self performSelectorOnMainThread:@selector(fieldUpload) withObject:nil waitUntilDone:NO];
        }
        
        strURL = nil;
        rangeStr = nil;
        subData = nil;
        [url release];
        url = nil;
        [request release];
        request = nil;
    }
    
    if (index == localVideo.total) {
        [self performSelectorOnMainThread:@selector(finishedOneUplaod) withObject:nil waitUntilDone:NO];
    }
}

- (void)reflashUI:(NSNumber *)progress
{
    if ([delegate respondsToSelector:@selector(uploadingWithProgress:)]) {
        [delegate uploadingWithProgress:[progress floatValue]];
    }
}

@end
